import React, { Component } from 'react';
import {
  KeyboardAvoidingView, StyleSheet, View, ActivityIndicator
} from 'react-native';

import { Provider, Toast } from '@ant-design/react-native';

import {
  Block, Text, Input, Button, Picker
} from '../components';
import { theme } from '../constants';
import { validateRegister } from '../utils/validator';
import NavigationUtil from '../navigation/NavigationUtil';
import Http from '../service/http';

export default class Register extends Component {
  constructor(props) {
    super(props);

    this.state = {
      userId: '',
      password: '',
      username: '',
      role: 0,
      phone: '',
      errors: [],
      loading: false
    };
  }

  handleRegister = async () => {
    const {
      errors, loading, ...requestBody
    } = this.state;
    const res = validateRegister(this.state);
    const newErrors = [];
    let msg = '';
    Object.keys(res).forEach((k) => {
      if (res[k] !== true) {
        // concat can't change itself
        msg += `${res[k][0]}\n`;
        newErrors.push(res[k][1]);
      }
    });
    if (newErrors.length !== 0) {
      this.setState({ errors: newErrors, loading: false });
      Toast.fail(msg, 2);
    } else {
      // not very good
      requestBody.username = requestBody.userId;

      const response = await Http.register(requestBody);
      const { status, message } = response.data;
      if (status === '200') {
        this.setState({ loading: false });
        Toast.success('注册成功，2秒后到登录页面', 2, () => {
          NavigationUtil.goPage('Login');
        });
      } else {
        Toast.fail(message, 2);
      }
    }
  }


  render() {
    const { loading, errors } = this.state;
    const hasErrors = (key) => (errors.includes(key) ? styles.hasErrors : null);
    return (
      <Provider>
        <KeyboardAvoidingView style={styles.signup} behavior="padding">
          <Block padding={[0, theme.sizes.base * 2]}>
            <Text h1 bold>
              注册
            </Text>
            <View style={{ flex: 1, flexDirection: 'column', justifyContent: 'center' }}>
              <Input
                label="工号"
                error={hasErrors('userId')}
                style={[styles.input, hasErrors('userId')]}
                onChangeText={(text) => {
                  this.setState({ userId: text });
                }}
              />
              <Input
                secure
                label="密码"
                error={hasErrors('password')}
                style={[styles.input, hasErrors('password')]}
                onChangeText={(text) => {
                  this.setState({ password: text });
                }}
              />
              <Input
                label="手机号码"
                error={hasErrors('phone')}
                style={[styles.input, hasErrors('phone')]}
                onChangeText={(text) => {
                  this.setState({ phone: text });
                }}
              />
              <Picker list={roleData} dftBtnValue="点击选择角色" onValueSelect={(value) => this.setState({ role: value })} />
              <Button gradient onPress={() => this.handleRegister()}>
                {loading
                  ? <ActivityIndicator size="small" color="white" /> : (
                    <Text bold white center h3>注册</Text>
                  )}
              </Button>
              <Button onPress={() => NavigationUtil.goPage('Login')}>
                <Text gray caption center style={{ textDecorationLine: 'underline' }}>
                  登录
                </Text>
              </Button>
            </View>
          </Block>
        </KeyboardAvoidingView>
      </Provider>
    );
  }
}

const roleData = [[
  { value: 1, label: '管理人员' },
  { value: 2, label: '工艺组' },
  { value: 3, label: '操作人员' }
]];

const styles = StyleSheet.create({
  signup: {
    flex: 1,
    justifyContent: 'center',
  },
  input: {
    borderRadius: 0,
    borderWidth: 0,
    borderBottomColor: theme.colors.gray2,
    borderBottomWidth: StyleSheet.hairlineWidth,
  },
  hasErrors: {
    borderBottomColor: theme.colors.accent,
  },
});
